import threading
import time
import os
import tkinter as tk
import tkinter.messagebox as messagebox
from src.audio_capture import AudioCapturer
from src.speech_recognition import SpeechRecognizer
from src.gui import SubtitleWindow
from src.config import AUDIO_SETTINGS, LANGUAGE_MAPPING, MODEL_PATHS


class RealTimeSubtitleApp:
    """主应用程序"""
    
    def __init__(self):
        # 初始化GUI
        self.gui = SubtitleWindow()
        
        # 显示下载对话框
        self.gui.show_download_dialog()
        
        # 初始化音频捕获
        self.capturer = AudioCapturer(
            AUDIO_SETTINGS['sample_rate'],
            AUDIO_SETTINGS['channels'],
            AUDIO_SETTINGS['device'],
            AUDIO_SETTINGS['chunk_size']
        )
        
        # 初始化语音识别器
        self.current_lang = self.get_valid_language()
        self.recognizer = SpeechRecognizer(self.current_lang)
        
        # 线程控制
        self.running = False
        self.processing_thread = None

    def start(self):
        """启动应用程序"""
        self.running = True
        try:
            self.capturer.start_capture()
        except Exception as e:
            messagebox.showerror("音频错误", f"无法启动音频捕获: {str(e)}")
            self.stop()
            return
        
        # 启动处理线程
        self.processing_thread = threading.Thread(target=self.process_audio)
        self.processing_thread.start()
        
        # 启动GUI
        self.gui.start()

    def process_audio(self):
        """音频处理线程"""
        while self.running:
            # 检查语言是否变更
            new_lang = self.gui.root.after(0, self.gui.get_selected_language)
            # 直接在主线程获取语言
            new_lang = self.gui.get_selected_language()
            
            if new_lang != self.current_lang:
                self.recognizer = SpeechRecognizer(new_lang)
                self.current_lang = new_lang
                
            # 获取音频数据
            audio_data = self.capturer.get_audio_data()
            if audio_data is not None:
                # 处理音频
                full_result, partial_result = self.recognizer.process_audio(audio_data)
                
                # 更新字幕
                if full_result:
                    self.gui.update_subtitle(full_result)
                elif partial_result:
                    self.gui.update_subtitle(partial_result)
            
            time.sleep(0.1)

    def stop(self):
        """停止应用程序"""
        self.running = False
        self.capturer.stop_capture()
        if self.processing_thread:
            self.processing_thread.join()
            
    def get_valid_language(self):
        """获取有效的已安装语言"""
        available = [code for code in MODEL_PATHS if os.path.exists(MODEL_PATHS[code])]
        if not available:
            messagebox.showerror("错误", "没有可用的语言模型")
            exit(1)
        # 优先使用用户选择的语言
        user_choice = self.gui.get_selected_language()
        return user_choice if user_choice in available else available[0]
            